package com.togo.lexical.analyzer.impl;

import com.togo.common.exception.ParseException;
import com.togo.common.model.token.*;
import com.togo.lexical.analyzer.LexicalAnalyzer;

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : taiyanan
 * Date    : 2022/1/29
 * Time    : 3:09 下午
 * ---------------------------------------
 * Desc    : TODO
 */
public class DefaultAnalyzer implements LexicalAnalyzer {

    private final String regex = "\\s*((//.*)|([0-9]+)|(\\w*)|(==|<=|>=|&&|\\|\\||\\p{Punct}))?";
    private final Pattern pattern = Pattern.compile(regex);

    private final LineNumberReader reader;
    private final Queue<Token> queue = new LinkedList<>();

    public DefaultAnalyzer(String s) {
        this.reader = new LineNumberReader(new StringReader(s));
    }

    public DefaultAnalyzer(Reader reader) {
        this.reader = new LineNumberReader(reader);
    }

    @Override
    public Token read() throws ParseException {
        if (hasNext()) {
            return queue.poll();
        } else {
            return EOFToken.instance();
        }
    }

    private boolean hasNext() {
        if (queue.isEmpty()) {
            String line = readLine();
            if (Objects.isNull(line)) {
                return false;
            } else {
                fillQueue(line);
            }
        }

        return true;
    }

    private void fillQueue(String line) {
        int lineNo = reader.getLineNumber();
        String[] strArr = line.split(" ");
        for (int i = 0; i < strArr.length; i++) {

            Matcher matcher = pattern.matcher(strArr[i].trim());

            if (matcher.lookingAt()) {
                addToken(lineNo, matcher);
            } else {
                throw new ParseException("bad token at line " + lineNo);
            }
        }

        queue.add(EOLToken.instance());
    }

    private void addToken(int lineNo, Matcher matcher) {
        String m = matcher.group(1);
        if (Objects.isNull(m)) {
            return;
        }
        // it is a comment
        if (Objects.nonNull(matcher.group(2))) {
            return;
        }

        if(Objects.nonNull(matcher.group(3))) {
            queue.add(new IntegerToken(Integer.parseInt(m), lineNo));
        } else if(Objects.nonNull(matcher.group(4))) {
            queue.add(new StringToken(m, lineNo));
        } else {
            queue.add(new IdentifierToken(m, lineNo));
        }
    }

    private String toStringLiteral(String string) {
        StringBuilder sb = new StringBuilder();
        int len = string.length() - 1;
        for (int i = 1; i < len; i++) {
            char c = string.charAt(i);
            if (c == '\\' && i + 1 < len) {
                int c2 = string.charAt(i + 1);
                if (c2 == '"' || c2 == '\\'){
                    c = string.charAt(++i);
                } else if (c2 == 'n') {
                    ++i;
                    c = '\n';
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }

    private String readLine() {

        try {
            return reader.readLine();
        } catch (IOException e) {
            throw new ParseException("", e);
        }
    }
}
